//
//  main.swift
//  demo
//
//  Created by zhaoke on 2023/6/9.
//

///  swiftui与combine代码示例
///
import Foundation

struct Student {
    let name: String
    let scores: [科目: Int]
}
enum 科目: String, CaseIterable {
    case 语文, 数学, 英语, 物理
}
//
let s1 = Student(
    name: "Jane",
    scores: [.语文: 86, .数学: 92, .英语: 73, .物理: 88]
)
let s2 = Student(
    name: "Tom",
    scores: [.语文: 99, .数学: 52, .英语: 97, .物理: 36]
)
let s3 = Student(
    name: "Emma",
    scores: [.语文: 91, .数学: 92, .英语: 100, .物理: 99]
)
let students = [s1, s2, s3]

//var best: (Student, Double)?
//for s in students {
//    var totalScore = 0
//    for key in 科目.allCases {
//        totalScore += s.scores[key] ?? 0
//    }
//    let averageScore = Double(totalScore) / Double(科目.allCases.count)
//    if let temp = best {
//        if averageScore > temp.1 {
//            best = (s, averageScore)
//        }
//    } else {
//        best = (s, averageScore)
//    }
//}
//if let best = best {
//    print("最高平均分：\(best.1), 姓名：\(best.0.name)")
//} else {
//    print("students为空")
//}

// 某个学生的平均分
func average(_ scores: [科目: Int]) -> Double {
    return Double(scores.values.reduce(0, +)) / Double(科目.allCases.count)
}
// 平均分最好的学生
let bestStudent = students
    .map { ($0, average($0.scores)) }
    .sorted { $0.1 > $1.1 }
    .first
print(bestStudent?.0.name ?? "")

// 求某个科目的平均数
func averageForType(_ type: 科目, student: [Student]) -> Double {
    let sum1 = student.reduce(0, { ($1.scores[.语文] ?? 0) + $0 })
    return Double(sum1) / Double(student.count)
}
print(averageForType(.语文, student: students))

// 某个科目的及格率
func passRate(_ obj: 科目, student: [Student]) -> (科目, Double) {
    var rate = Double(student.reduce(0, { $1.scores[obj] ?? 0 >= 60 ? $0+1 : $0 })) / Double(student.count)
    return (obj, rate)
}
var sortRate = 科目.allCases.map({ passRate($0, student: students) }).sorted { $0.1 > $1.1 }
print(sortRate)


